package com.mall.common.security.utils;

import com.alibaba.fastjson.JSONObject;
import com.mall.common.core.asserts.ApiAssert;
import com.mall.common.core.cons.AuthCons;
import com.mall.common.core.enums.ErrorCodeEnum;
import com.mall.common.core.model.entity.LoginInfo;
import com.mall.common.redis.utils.RedisUtils;
import com.mall.common.security.framework.aware.ApplicationUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * API工具类
 *
 * @author Sam
 */
@SuppressWarnings("ALL")
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class ApiUtils {

    /**
     * 获取当前用户id,从jwt获取
     */
    public static String getToken() {
        String token = ApplicationUtils.getRequest().getHeader("Authorization");
        ApiAssert.notNull(ErrorCodeEnum.UNAUTHORIZED, token);
        //Authorization: Bearer <token>
        token = token.replaceFirst("Bearer ", "");
        ApiAssert.isFalse(ErrorCodeEnum.UNAUTHORIZED, JWTUtils.isExpired(token));
        return token;
    }

    /**
     * 获取当前用户id,从jwt获取
     */
    public static String currentUid() {
        return JWTUtils.getUid(getToken());
    }

    /**
     * 获取登录用户信息 redis
     *
     * @return
     */
    public static LoginInfo loginUser() {
        // 获取请求携带的令牌
        String token = getToken();
        RedisUtils redisUtils = ApplicationUtils.getBean(RedisUtils.class);
        String userInfo = redisUtils.get(AuthCons.USER_INFO_TOKEN + token);
        ApiAssert.notStrEmpty(ErrorCodeEnum.UNAUTHORIZED, userInfo);
        return JSONObject.parseObject(userInfo, LoginInfo.class);
    }

}
